<?php

declare (strict_types=1);
namespace App\Model;

use Hyperf\DbConnection\Db;

/**
 * @property int $id 运费配置id
 * @property int $tpl_id 模板id
 * @property int $rule_id 规则模板id
 * @property string $first_num 首重
 * @property string $first_price 首费
 * @property string $add_num 续重每xx
 * @property string $add_price 续费单价
 * @property string $tpl_type 1商品2高优先级 3低优先级
 * @property int $area_free 此区域固定免邮1是 0否
 * @property int $free_min_price 订单规则类，满xxx元免邮
 */
class DeliveryRule extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'fly_delivery_rule';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'tpl_id' => 'integer', 'rule_id' => 'integer', 'area_free' => 'integer', 'free_min_price' => 'integer'];

    public function provinces(){
        return $this
            ->hasMany(DeliveryRuleArea::class,'rule_id','id')
            ->with('province')
            ->with('province_child')
            ->select([
                Db::raw('any_value(rule_id) as rule_id'),
                Db::raw('any_value(id) as id') ,
                Db::raw('any_value(province_id) as province_id') ,
                Db::raw('any_value(tpl_id) as tpl_id') ,
                Db::raw('any_value(city_id) as city_id') ,
                Db::raw('any_value(area_id) as area_id') ,
            ])
            ->groupBy(['rule_id','province_id'])
            ;
    }

    public function citys(){
        return $this
            ->hasMany(DeliveryRuleArea::class,'rule_id','id')
            ->with('city')
            ->with('city_child')
            ->where('city_id','!=','0')
//            ->withCount('city_child')
            ->groupBy(['rule_id','city_id'])
            ->select([
                Db::raw('any_value(rule_id) as rule_id'),
                Db::raw('any_value(id) as id') ,
                Db::raw('any_value(province_id) as province_id') ,
                Db::raw('any_value(tpl_id) as tpl_id') ,
                Db::raw('any_value(city_id) as city_id') ,
                Db::raw('any_value(area_id) as area_id') ,
            ])
            ;
    }
    public function areas(){
        return $this
            ->hasMany(DeliveryRuleArea::class,'rule_id','id')
            ->with('area')
            ->where('area_id','!=','0')
            ->groupBy(['rule_id','area_id'])
            ->select([
                Db::raw('any_value(rule_id) as rule_id'),
                Db::raw('any_value(id) as id') ,
                Db::raw('any_value(province_id) as province_id') ,
                Db::raw('any_value(tpl_id) as tpl_id') ,
                Db::raw('any_value(city_id) as city_id') ,
                Db::raw('any_value(area_id) as area_id') ,
            ])
            ;
    }


}